package org.or5e.plugin.core;

import java.io.FileNotFoundException;
import java.io.FileReader;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;

import org.or5e.core.plugin.Plugin;
import org.or5e.core.plugin.PluginException;
import org.or5e.core.plugin.PluginLifecycleAdaptor;
import org.or5e.plugin.pojo.itunes.Plist;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;


public class ITunesSyncPlugin extends PluginLifecycleAdaptor {

	@Override public String getPluginID() {
		return "ItunesSync_001";
	}

	@Override public void initilize() throws PluginException {
		info("Initilizing the ITunes Sync Plugin...");
	}

	@Override public void destroy() {
		info("Destroying the ITunes Sync Plugin..."+isProcessing());
	}

	@Override public void doProcess() {
		info("Processing the ITunes Sync Plugin...");
		JAXBContext context;
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
	        spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
	        XMLReader xmlReader = spf.newSAXParser().getXMLReader();
	        InputSource inputSource = new InputSource(new FileReader(getProperties("itunes-xml")));
	        SAXSource source = new SAXSource(xmlReader, inputSource);

	        context = JAXBContext.newInstance(org.or5e.plugin.pojo.itunes.Plist.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			unmarshaller.setSchema(null);
			Plist pList = (Plist) unmarshaller.unmarshal(source);
			ITunesHelper.getITunesHelper().parseAndLoadTrackDetails(pList);
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (SAXNotRecognizedException e) {
			e.printStackTrace();
		} catch (SAXNotSupportedException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	};

	@Override public String getName() {
		return "ItunesSync";
	}

	public static void main(String[] args) {
		Plugin plugin = new ITunesSyncPlugin();
		plugin.doThreadedProcess();
		System.out.println("Done...");
	}
}